<template>
  <div>
    <el-form :model="sysMenuQuery" inline ref="searchFormRef">
      <el-form-item label="菜单名称" prop="menuName">
        <el-input v-model="sysMenuQuery.keyword"></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
            v-model="sysMenuQuery.status"
            placeholder="请选择状态"
            style="width: 240px"
        >
          <el-option label="正常" :value="0"/>
          <el-option label="禁用" :value="1"/>
          <el-option label="全部" :value="-1"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button :icon="Search" @click="getSysMenuList">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button :icon="Refresh" type="primary" @click="resetSearch(searchFormRef)"
        >重置
        </el-button>
      </el-form-item>
    </el-form>
    <el-space wrap>
      <el-button :icon="Plus" size="small" type="primary" @click="createMenu(0)"
      >新增
      </el-button>
      <el-button :icon="Download" size="small">导入</el-button>
      <el-button :icon="Upload" size="small">导出</el-button>
    </el-space>
    <el-table :data="menuList" row-key="menuId" v-loading="loading">
      <el-table-column prop="menuId" label="编号"/>
      <el-table-column prop="menuName" label="名称"/>
      <el-table-column label="图标">
        <template #default="scope">
          <el-icon :size="30">
            <component
                :is="scope.row.icon"
                class="icon-size"
                v-if="scope.row.icon"
            ></component>
          </el-icon>
        </template>
      </el-table-column>
      <el-table-column prop="menuCode" label="标识"/>
      <el-table-column prop="status" label="状态">
        <template #default="scope">
          <el-tag v-if="scope.row.status == 0">启用</el-tag>
          <el-tag v-else type="danger">禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="component" label="组件"/>
      <el-table-column prop="path" label="路由"/>
      <el-table-column prop="createTime" label="创建时间">
        <template #default="scope">
          {{ $timeFormat(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="220px">
        <template #default="scope">
          <div class="flex-hcenter">
            <el-button :icon="EditPen" size="small" type="warning" @click="modifySysMenu(scope.row)">
              修改
            </el-button>
            <el-divider direction="vertical"/>
            <el-button :icon="Plus" size="small" type="primary" @click="createMenu(scope.row.menuId)" :disabled="scope.row.type===2">新增
            </el-button>
            <el-divider direction="vertical"/>
            <el-button :icon="Delete" size="small" type="danger" @click="deleteMenu(scope.row.menuId)">
              删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
        v-model="dialogFormVisible"
        :title="dialogIsAdd ? '新增' : '修改'"
        width="600"
        draggable
        @close="resetSysMenuForm"
    >
      <el-form :model="sysMenuForm" label-width="100" :rules="rules" ref="ruleFormRef">
        <el-form-item label="图标" prop="icon">
          <el-input v-model="sysMenuForm.icon"></el-input>
        </el-form-item>
        <el-form-item label="权限标识" prop="menuCode">
          <el-input v-model="sysMenuForm.menuCode" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="权限名称" prop="menuName">
          <el-input v-model="sysMenuForm.menuName"></el-input>
        </el-form-item>
        <el-form-item label="父级" prop="parentId">
          <el-tree-select
              style="max-width: 500px"
              check-strictly
              node-key="menuId"
              v-model="sysMenuForm.parentId"
              :data="parentMenuList"
              :props="defaultProps"
              show-checkbox
          />
        </el-form-item>
        <el-form-item label="权限类型" prop="type">
          <el-radio-group v-model="sysMenuForm.type">
            <el-radio :value="0">目录</el-radio>
            <el-radio :value="1">页面</el-radio>
            <el-radio :value="2">按钮</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="component">
          <template #label>
            <el-tooltip
                effect="dark"
                content="组件所在位置（仅当前组件）"
                placement="top-start"
            >
              <el-text>
                组件位置
                <el-icon>
                  <QuestionFilled/>
                </el-icon>
              </el-text>
            </el-tooltip>
          </template>
          <el-input v-model="sysMenuForm.component"></el-input>
        </el-form-item>
        <el-form-item label="访问路由" prop="path">
          <template #label>
            <el-tooltip
                effect="dark"
                content="当前路径，不包括父级路由"
                placement="top-start"
            >
              <el-text>
                访问路由
                <el-icon>
                  <QuestionFilled/>
                </el-icon>
              </el-text>
            </el-tooltip>
          </template>
          <template #default>
            <el-input v-model="sysMenuForm.path"></el-input>
          </template>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="sysMenuForm.status">
            <el-radio :value="0">启用</el-radio>
            <el-radio :value="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否显示" prop="visible">
          <el-radio-group v-model="sysMenuForm.visible">
            <el-radio :value="0">显示</el-radio>
            <el-radio :value="1">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否可关闭" prop="closable">
          <el-radio-group v-model="sysMenuForm.closable">
            <el-radio :value="0">可以关闭</el-radio>
            <el-radio :value="1">不可关闭</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitSaveMenuForm(ruleFormRef)">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import {reactive, ref, onMounted, watch} from "vue";
import {
  Plus,
  Search,
  Refresh,
  EditPen,
  Delete,
  QuestionFilled,
  Download,
  Upload
} from "@element-plus/icons-vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {useUserStore} from "@/stores/user";
import {
  reqCreateMenu,
  reqDeleteMenuById,
  reqGetMenuTreeList,
  reqGetParentMenuList,
  reqUpdateMenu
} from "@/api/system/menu.js";

const userStore = useUserStore();
let loading = ref(true)
let menuList = ref([]);
let parentMenuList = reactive([
  {
    menuId: 0,
    menuCode: "",
    menuName: "一级菜单",
    parentId: 0,
    createTime: "",
    creator_id: "",
    path: "",
    component: "",
    type: 0,
    status: 0,
    description: "",
    icon: "",
    closable: 0,
    visible: 0,
    children: [],
  },
]);
let sysMenuQuery = reactive({
  keyword: "",
  status: -1,
});
let dialogIsAdd = ref(true);
let dialogFormVisible = ref(false);
let sysMenuForm = reactive({
  menuId: null,
  menuCode: "",
  menuName: "",
  parentId: 0,
  createTime: "",
  createBy: "",
  path: "",
  component: "",
  type: 0,
  status: 0,
  remark: "",
  icon: "",
  closable: 0,
  visible: 0,
});
const ruleFormRef = ref();
let searchFormRef = ref();
let rules = reactive({
  menuCode: [{required: true, message: "请输入权限标识", trigger: "blur"}],
  menuName: [{required: true, message: "请输入权限名称", trigger: "blur"}],
  parentId: [{required: true, message: "请输入父级菜单", trigger: "blur"}],
  type: [{required: true, message: "请输入权限名称", trigger: "blur"}],
});

function resetSearch(formEl) {
  if (!formEl) return;
  formEl.resetFields();
}

let getSysMenuList = async () => {
  let res = await reqGetMenuTreeList(sysMenuQuery)
  menuList.value = res.data;
  loading.value = false
}

/**
 * 手动重置表单，新增和修改采用同一个表单，element-plus表单重置会出现bug
 * **/
function resetSysMenuForm() {
  sysMenuForm.menuId = null;
  sysMenuForm.menuCode = "";
  sysMenuForm.menuName = "";
  sysMenuForm.parentId = 0;
  sysMenuForm.createTime = "";
  sysMenuForm.createBy = "";
  sysMenuForm.path = "";
  sysMenuForm.component = "";
  sysMenuForm.type = 0;
  sysMenuForm.status = 0;
  sysMenuForm.icon = "";
  sysMenuForm.closable = 0;
  sysMenuForm.visible = 0;
  dialogIsAdd.value = true;
}

async function modifySysMenu(menu) {
  Object.assign(sysMenuForm, menu);
  dialogIsAdd.value = false;
  dialogFormVisible.value = true;
}

function createMenu(parentId) {
  sysMenuForm.parentId = parentId;
  dialogIsAdd.value = true;
  dialogFormVisible.value = true;
}

let submitSaveMenuForm = async (formEl) => {
  if (!formEl) return; //表单校验
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (dialogIsAdd.value) {
        await reqCreateMenu(sysMenuForm);
      } else {
        await reqUpdateMenu(sysMenuForm);
      }
    } else {
      console.log("error submit!", fields);
    }
  });
  await getSysMenuList();
  dialogFormVisible.value = false;
};

function deleteMenu(menuId) {
  ElMessageBox.confirm("删除之后无法恢复，请确认是否删除？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
      .then(() => {
        reqDeleteMenuById(menuId).then(() => {
          ElMessage({
            message: "删除成功！",
            type: "success",
          });
        });
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "取消删除！",
        });
      });
}

let getParentMenuList = () => {
  return reqGetParentMenuList().then((res) => {
    parentMenuList[0].children = res.data;
  });
};
onMounted(() => {
  getSysMenuList();
  getParentMenuList()
});

const defaultProps = {
  children: "children",
  label: "menuName",
};
</script>
<style></style>
